<template>
  <div class="log-form-container">
    <el-form ref="form" :model="formData" :rules="rules" label-width="100px">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="定位器" prop="locatorId">
            <el-select
              v-model="formData.locatorId"
              placeholder="请选择定位器"
              filterable
              remote
              :remote-method="searchLocators"
              :loading="locatorLoading"
              @change="handleLocatorChange"
              style="width: 100%"
            >
              <el-option
                v-for="item in locatorOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
                <span style="float: left">{{ item.label }}</span>
                <span v-if="item.containerCode" style="float: right; color: #8492a6; font-size: 13px">
                  {{ item.containerCode }} | {{ item.materialCode }}
                </span>
                <span v-else style="float: right; color: #8492a6; font-size: 13px">未绑定器具</span>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="器具" prop="containerId">
            <el-input
              v-model="containerInfo"
              placeholder="选择定位器后自动显示绑定的器具"
              readonly
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="上传时间" prop="uploadTime">
            <el-date-picker
              v-model="formData.uploadTime"
              type="datetime"
              placeholder="选择上传时间"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="电池电量" prop="batteryLevel">
            <el-slider
              v-model="formData.batteryLevel"
              :min="0"
              :max="100"
              :step="1"
              show-input
              input-size="mini"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 位置信息选择 -->
      <el-form-item label="位置信息">
        <el-tabs v-model="locationInputType" @tab-click="handleTabClick">
          <el-tab-pane label="手动输入" name="manual">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="经度" prop="longitude">
                  <el-input
                    v-model="formData.longitude"
                    placeholder="请输入经度"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="纬度" prop="latitude">
                  <el-input
                    v-model="formData.latitude"
                    placeholder="请输入纬度"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="上传地址" prop="uploadAddress">
              <el-input
                v-model="formData.uploadAddress"
                placeholder="请输入上传地址"
              />
            </el-form-item>
          </el-tab-pane>
          
          <el-tab-pane label="地图选择" name="map">
            <div class="map-picker-section">
              <map-picker
                ref="mapPicker"
                :value="mapPickerValue"
                :height="'350px'"
                @confirm="handleMapPickerConfirm"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form-item>

      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="温度" prop="temperature">
            <el-input-number
              v-model="formData.temperature"
              :min="-50"
              :max="100"
              :step="0.1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="湿度" prop="humidity">
            <el-input-number
              v-model="formData.humidity"
              :min="0"
              :max="100"
              :step="1"
              controls-position="right"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="震动等级" prop="shockLevel">
            <el-select v-model="formData.shockLevel" placeholder="请选择震动等级" style="width: 100%">
              <el-option label="1级（轻微）" :value="1" />
              <el-option label="2级（一般）" :value="2" />
              <el-option label="3级（中等）" :value="3" />
              <el-option label="4级（强烈）" :value="4" />
              <el-option label="5级（剧烈）" :value="5" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="其他数据" prop="otherData">
        <el-input
          v-model="formData.otherData"
          type="textarea"
          :rows="3"
          placeholder="请输入其他数据（JSON格式）"
        />
      </el-form-item>
    </el-form>
    
    <!-- 底部操作区域 -->
    <div class="drawer-footer">
      <el-button type="primary" @click="submitForm" :loading="submitLoading">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </div>
</template>

<script>
import { listLocator } from "@/api/pack/locator";
import { getLocationLog } from "@/api/pack/locationLog";
import MapPicker from "@/components/MapPicker";

export default {
  name: "LogForm",
  components: {
    MapPicker
  },
  props: {
    form: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      // 表单数据
      formData: {
        logId: undefined,
        locatorId: undefined,
        containerId: undefined,
        uploadTime: undefined,
        latitude: undefined,
        longitude: undefined,
        uploadAddress: '',
        batteryLevel: 100,
        temperature: 25,
        humidity: 50,
        shockLevel: 1,
        otherData: ''
      },
      // 位置输入类型
      locationInputType: 'manual',
      // 表单校验
      rules: {
        locatorId: [
          { required: true, message: "请选择定位器", trigger: "change" }
        ],
        uploadTime: [
          { required: true, message: "请选择上传时间", trigger: "change" }
        ],
        latitude: [
          { required: true, message: "请输入纬度", trigger: "blur" },
          { pattern: /^-?([0-8]?[0-9]|90)(\.[0-9]{1,10})?$/, message: "纬度格式不正确", trigger: "blur" }
        ],
        longitude: [
          { required: true, message: "请输入经度", trigger: "blur" },
          { pattern: /^-?((1?[0-7]?|[0-9]?)[0-9]|180)(\.[0-9]{1,10})?$/, message: "经度格式不正确", trigger: "blur" }
        ],
        batteryLevel: [
          { required: true, message: "请输入电池电量", trigger: "blur" }
        ],
        temperature: [
          { required: true, message: "请输入温度", trigger: "blur" }
        ],
        humidity: [
          { required: true, message: "请输入湿度", trigger: "blur" }
        ],
        shockLevel: [
          { required: true, message: "请选择震动等级", trigger: "change" }
        ]
      },
      // 定位器选项
      locatorOptions: [],
      // 定位器加载状态
      locatorLoading: false,
      // 提交加载状态
      submitLoading: false,
      // 器具信息
      containerInfo: ''
    };
  },
  computed: {
    // 地图选择器的值
    mapPickerValue() {
      if (this.formData.longitude && this.formData.latitude) {
        return {
          longitude: parseFloat(this.formData.longitude),
          latitude: parseFloat(this.formData.latitude),
          address: this.formData.uploadAddress
        };
      }
      return null;
    }
  },
  created() {
    this.init();
  },
  methods: {
    // 初始化
    init() {
      // 如果有ID，则获取详情
      if (this.form.logId) {
        getLocationLog(this.form.logId).then(response => {
          this.formData = response.data;
          // 设置器具信息显示
          if (this.formData.containerCode && this.formData.materialCode) {
            this.containerInfo = `${this.formData.containerCode} | ${this.formData.materialCode}`;
          } else if (this.formData.containerCode) {
            this.containerInfo = this.formData.containerCode;
          } else {
            this.containerInfo = '未绑定器具';
          }
        });
      } else {
        // 否则使用默认值
        this.formData = {
          ...this.formData,
          ...this.form,
          uploadTime: this.form.uploadTime || this.parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        };
        this.containerInfo = '';
      }
      
      // 加载定位器和器具选项
      this.loadLocatorOptions();
    },
    
    // 加载定位器选项
    loadLocatorOptions() {
      this.locatorLoading = true;
      listLocator({ pageSize: 100 }).then(response => {
        this.locatorOptions = response.rows.map(item => ({
          value: item.locatorId,
          label: item.locatorCode,
          containerCode: item.containerCode,
          materialCode: item.materialCode,
          containerId: item.containerId
        }));
        this.locatorLoading = false;
      }).catch(() => {
        this.locatorLoading = false;
      });
    },
    
    // 搜索定位器
    searchLocators(query) {
      if (query) {
        this.locatorLoading = true;
        listLocator({ locatorCode: query, pageSize: 20 }).then(response => {
          this.locatorOptions = response.rows.map(item => ({
            value: item.locatorId,
            label: item.locatorCode,
            containerCode: item.containerCode,
            materialCode: item.materialCode,
            containerId: item.containerId
          }));
          this.locatorLoading = false;
        }).catch(() => {
          this.locatorLoading = false;
        });
      }
    },
    
    // 定位器变更
    handleLocatorChange(locatorId) {
      // 如果选择了定位器，设置对应的器具信息
      if (locatorId) {
        const selectedLocator = this.locatorOptions.find(item => item.value === locatorId);
        if (selectedLocator) {
          this.formData.containerId = selectedLocator.containerId;
          if (selectedLocator.containerCode && selectedLocator.materialCode) {
            this.containerInfo = `${selectedLocator.containerCode} | ${selectedLocator.materialCode}`;
          } else {
            this.containerInfo = '未绑定器具';
          }
        } else {
          this.formData.containerId = undefined;
          this.containerInfo = '未绑定器具';
        }
      } else {
        this.formData.containerId = undefined;
        this.containerInfo = '';
      }
    },
    

    

    
    // 处理标签页切换
    handleTabClick(tab) {
      this.locationInputType = tab.name;
    },
    
    // 处理地图选择器确认
    handleMapPickerConfirm(position) {
      this.formData.longitude = position.longitude.toString();
      this.formData.latitude = position.latitude.toString();
      this.formData.uploadAddress = position.address || '';
      
      // 切换到手动输入标签页显示结果
      this.locationInputType = 'manual';
      
      this.$message.success('位置信息已选择');
    },
    
    // 提交表单
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.submitLoading = true;
          
          // 转换数据类型
          const submitData = {
            ...this.formData,
            latitude: parseFloat(this.formData.latitude),
            longitude: parseFloat(this.formData.longitude),
            batteryLevel: parseInt(this.formData.batteryLevel),
            temperature: parseFloat(this.formData.temperature),
            humidity: parseInt(this.formData.humidity)
          };
          
          this.$emit('submit', submitData);
          this.submitLoading = false;
        }
      });
    },
    
    // 取消
    cancel() {
      this.$emit('cancel');
    },
    
    // 格式化时间
    parseTime(time, pattern) {
      if (!time) {
        return null;
      }
      const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
      let date;
      if (typeof time === 'object') {
        date = time;
      } else {
        if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
          time = parseInt(time);
        } else if (typeof time === 'string') {
          time = time.replace(new RegExp(/-/gm), '/');
        }
        if ((typeof time === 'number') && (time.toString().length === 10)) {
          time = time * 1000;
        }
        date = new Date(time);
      }
      const formatObj = {
        y: date.getFullYear(),
        m: date.getMonth() + 1,
        d: date.getDate(),
        h: date.getHours(),
        i: date.getMinutes(),
        s: date.getSeconds(),
        a: date.getDay()
      };
      const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
        let value = formatObj[key];
        // Note: getDay() returns 0 on Sunday
        if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value]; }
        if (result.length > 0 && value < 10) {
          value = '0' + value;
        }
        return value || 0;
      });
      return time_str;
    }
  }
};
</script>

<style lang="scss" scoped>
.log-form-container {
  padding: 20px;
  height: 100%;
  overflow-y: auto;
  box-sizing: border-box;
  position: relative;
  padding-bottom: 60px;
}

.map-picker-section {
  margin-top: 10px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
  
  :deep(.map-picker-container) {
    .map-container {
      border: none;
      border-radius: 0;
    }
  }
}

.drawer-footer {
  position: fixed;
  bottom: 0;
  right: 0;
  padding: 10px 20px;
  background: #fff;
  text-align: right;
  z-index: 10;
}
</style> 